package com.course.rabbitmq.netty;

import com.alibaba.fastjson.JSONObject;

import java.util.Objects;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 基于多线程方式手写MQ-单机版本
 * @Author: 涂玄武
 * @DATE: 2021/6/16 10:11
 */
public class ThreadMQ {

    /**
     * 链表阻塞双端队列
     */
    private static LinkedBlockingDeque<JSONObject> msgs = new LinkedBlockingDeque<>();

    public static void main(String[] args) {

        //生产者线程
        Thread producerThread = new Thread(() -> {
            try {
                while (true) {
                    Thread.sleep(1000L);
                    JSONObject data = new JSONObject();
                    data.put("userId", "1234");
                    msgs.offer(data);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者");

        producerThread.start();

        //消费者线程
        Thread consumerThread = new Thread(() -> {
            try {
                while (true) {
                    JSONObject data = msgs.poll();
                    if (Objects.nonNull(data)) {
                        System.out.println(Thread.currentThread().getName() + ":" + data);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "消费者");

        consumerThread.start();
    }

}
